#include "stdafx.h"
#include "Debug.h"

using namespace MomogenkyouHelper;
using namespace MomogenkyouSystem;

FONT						DebugConsole::g_pDebugFont(NULL);
TEXTURE						DebugConsole::g_pBlankTexture(NULL);
RECT						DebugConsole::g_Rectangle;
std::deque<std::string>		DebugConsole::g_Messages;
bool						DebugConsole::g_bVisible(false);

void	DebugConsole::Initialize()
{
	g_Rectangle.top		= 0;
	g_Rectangle.left	= 0;
	g_Rectangle.right	= 800;
	g_Rectangle.bottom	= 450;

	HRESULT _Result = D3DXCreateTextureFromFile(GraphicsSystem::Device, L"Data/Base/BlankTexture.png", &g_pBlankTexture);
	ASSERT(_Result == S_OK, "Error creating BlankTexture");

	_Result	=	D3DXCreateFont(	GraphicsSystem::Device,
								16,
								8,
								FW_NORMAL,
								NULL,
								FALSE,
								SHIFTJIS_CHARSET,
								OUT_DEFAULT_PRECIS,
								ANTIALIASED_QUALITY,
								FIXED_PITCH | FF_MODERN,
								L"tahoma",
								&g_pDebugFont);

	ASSERT(_Result == S_OK, "Error creating Font");
}

void	DebugConsole::Shutdown()
{
	g_pDebugFont->Release();
	g_pBlankTexture->Release();
}

void	DebugConsole::WriteConsoleLine(std::string Text, ...)
{
	char    Buffer[2048], * p = Buffer;
	va_list args;
	int     n;
	va_start(args, Text);
	n = _vsnprintf_s(p, sizeof Buffer - 3, 2047, Text.c_str(), args);
	p += (n < 0) ? sizeof Buffer - 3 : n;
	while ( p > Buffer  &&  isspace(p[-1]) )
		*--p = '\0';

	*p++ = '\r';
	*p++ = '\n';
	*p   = '\0';

	std::string Message = Buffer;
	g_Messages.push_front(Message.substr(0, Message.length() - 1));
	if(g_Messages.size() > 20)
		g_Messages.pop_back();
}

void	DebugConsole::Update(const float & fInterval)
{
	fInterval;
	if(MomogenkyouSystem::InputSystem::KeyReleased(DIK_F6))
		g_Messages.clear();

	if(MomogenkyouSystem::InputSystem::KeyReleased(DIK_F5))
		g_bVisible = !g_bVisible;
}

void	DebugConsole::Render()
{
	if(!g_bVisible) return;
	GraphicsSystem::SpriteBatch->Begin(0);
	GraphicsSystem::SpriteBatch->Draw(g_pBlankTexture, &g_Rectangle, NULL, NULL, ARGB(150, 0, 0, 0));
	
	RECT rect = {0, 16 * 19, 512, 512};

	for(size_t i = 0; i < g_Messages.size(); i++)
	{
		g_pDebugFont->DrawTextA(GraphicsSystem::SpriteBatch, g_Messages[i].c_str(), g_Messages[i].length(), &rect, DT_LEFT | DT_TOP, ARGB(255, 255, 255, 255));
		rect.top -= 16;
	}
	GraphicsSystem::SpriteBatch->End();
}